﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;

namespace Urbania.GUI.XML
{
    public static class XMLHandler
    {
        public static Elements.Frame XMLDeconstructor(ref LuaVM lua, string xml)
        {
            List<Elements.Frame> frames = new List<Elements.Frame>();
            XDocument doc = XDocument.Parse(xml);

            var frame = from x in doc.Descendants("PopUp")
                        select new{
                                rect = new Microsoft.Xna.Framework.Rectangle(
                                    (int)Convert.ToInt16(x.Descendants("rectangleX").First().Value),
                                    (int)Convert.ToInt16(x.Descendants("rectangleY").First().Value),
                                    (int)Convert.ToInt16(x.Descendants("width").First().Value),
                                    (int)Convert.ToInt16(x.Descendants("height").First().Value))
                                
                        };
            frames.Add(new Elements.Frame(ref lua));

            foreach (var p in frame)
            {
                frames[0].AddPopUp(p.rect);
            }

            return frames[0];
        }

        public static void Serialize<T>(T t) where T : class
        {
            XmlSerializer s = new XmlSerializer(typeof(T));
            TextWriter w = new StreamWriter(@"testXml.xml");
            s.Serialize(w, t);
            w.Close();
        }

        public static T DeSerialize<T>(string xmlFilePath) where T : class
        {
            TextReader r = new StreamReader(xmlFilePath);
            XmlSerializer s = new XmlSerializer(typeof(T));
            object o = s.Deserialize(r);
            T t = (T)o;
            return t;
        }

        //public static Elements.Button GetButton()
        //{
        //    var button = from x in doc.Descendants("Button")
        //                select new
        //                {
        //                    v2 = new Microsoft.Xna.Framework.Vector2((float)Convert.ToInt16(x.Descendants("positionX").First().Value),
        //                    (float)Convert.ToInt16(x.Descendants("positionY").First().Value)),
        //                    text = x.Descendants("text").First().Value,
        //                    designType = x.Descendants("designType").First().Value,
        //                    script = x.Descendants("script").First().Value,
        //                    name = x.Descendants("name").First().Value

        //                };
        //    Elements.Button b = (Elements.Button)button;
        //    return b;
        //}
    }
}
